package com.ymatou.iapi.shoppingcart.testcase;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.shoppingcart.parameter.GetShoppingCartListBean;
import com.ymatou.iapi.shoppingcart.parameter.YmtShoppcartListProductBean;
import com.ymatou.iapi.shoppingcart.service.GetShoppingCartListCall;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.AssertService;
import com.ymttest.business.service.BuyerAppProdService;
import com.ymttest.business.service.BuyerAppShoppingCartService;
import com.ymttest.business.service.LiveCallService;
import com.ymttest.business.service.SellerProductCallService;
import com.ymttest.database.mongo.LiveProductModelWapper;
import com.ymttest.database.mongo.ProductDetailModelWapper;
import com.ymttest.database.mongo.ShoppingCartMongoWapper;
import com.ymttest.database.mongo.YmtShoppingCartBean;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.constant.JsonBeanFile;

public class Ts_GetShoppingCartList {
	
	private static GetShoppingCartListBean getShoppingCartListBean;
	private static GetShoppingCartListCall getShoppingCartListCall;
	
	private static int buyerUserId = 20226821;
	private static int sellerId = Integer.parseInt(EnvSetup.getData("zhangyi_seller002_id"));
	private static String sellerName = EnvSetup.getData("zhangyi_seller002_name");
	private static String fileName = JsonBeanFile.CreateLiveForZyTpl;
	
	private static int activityStartId = Integer.parseInt(EnvSetup.getData("productActivityStartId"));
	private static String activityUser = EnvSetup.getData("AdminLoginUser");
	private static String activityPswd = EnvSetup.getData("AdminLoginPswd");
	
	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("获取购物车商品列表");
	}

	@Before
	public void caseUp() throws Exception {
		getShoppingCartListBean = new GetShoppingCartListBean();
		getShoppingCartListCall = new GetShoppingCartListCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(getShoppingCartListCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Ts_GetShoppingCartList_001() {
		 Logger.start(true,"验证购物车商品的总数量");
		 try {
			 String OffSaleProductId = SellerProductCallService.addNewProductOnSale(sellerId, 
					 sellerName, null).getJSONObject("Data").getString("ProductID");
			 String productId = SellerProductCallService.addNewProductOnSale(sellerId, 
					 sellerName, null).getJSONObject("Data").getString("ProductID");
			 
			 BuyerAppShoppingCartService buyerAppShoppingCartService = new BuyerAppShoppingCartService();
			 buyerAppShoppingCartService.addShoppingCart(OffSaleProductId, buyerUserId, 1);
			 buyerAppShoppingCartService.addShoppingCart(productId, buyerUserId, 1);
			 
			 SellerProductCallService.batchSetProductOffSale(OffSaleProductId, sellerId);
			 
			 getShoppingCartListBean.setExcludeSellerCoupon(false);
			 getShoppingCartListBean.setGroupByPromotion(true);
			 getShoppingCartListBean.setUserId(buyerUserId);
			 
			 getShoppingCartListCall.setData(getShoppingCartListBean);
			 getShoppingCartListCall.callService();
			 
			 Logger.comment("getShoppingCartListCall send:" + getShoppingCartListCall.getEntityString());
			 Logger.comment("getShoppingCartListCall response:" + getShoppingCartListCall.getReturnData());
			 
			 ShoppingCartMongoWapper shoppingCartMongoWapper = new ShoppingCartMongoWapper();
			 ArrayList<YmtShoppingCartBean> notInfo = (ArrayList<YmtShoppingCartBean>) shoppingCartMongoWapper.getYmtShoppingCartInfoList("{'userid':" + buyerUserId + "}", 101);
			 
			 Logger.verifyEquals(notInfo.size(), getShoppingCartListCall.getResult().getInt("totalNum"), "验证购物车总数量是否一致");
			 
		 } catch (Exception e) {
			 Logger.fail(e);
		 }
	 }
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Ts_GetShoppingCartList_002() {
		 Logger.start(true,"验证购物车列表的失效商品数据");
		 try {
			 String productId = SellerProductCallService.addNewProductOnSale(sellerId, 
					 sellerName, null).getJSONObject("Data").getString("ProductID");
			 
			 BuyerAppShoppingCartService buyerAppShoppingCartService = new BuyerAppShoppingCartService();
			 buyerAppShoppingCartService.clearInvalidProductList(buyerUserId);
			 buyerAppShoppingCartService.addShoppingCart(productId, buyerUserId, 1);
			 
			 SellerProductCallService.batchSetProductOffSale(productId, sellerId);
			 
			 getShoppingCartListBean.setExcludeSellerCoupon(false);
			 getShoppingCartListBean.setGroupByPromotion(true);
			 getShoppingCartListBean.setUserId(buyerUserId);
			 
			 getShoppingCartListCall.setData(getShoppingCartListBean);
			 getShoppingCartListCall.callService();
			 
			 Logger.comment("getShoppingCartListCall send:" + getShoppingCartListCall.getEntityString());
			 Logger.comment("getShoppingCartListCall response:" + getShoppingCartListCall.getReturnData());
			 
			 this.verifyInvalidProdListData(getShoppingCartListCall);
			 
		 } catch (Exception e) {
			 Logger.fail(e);
		 }
	 }
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Ts_GetShoppingCartList_003() {
		 Logger.start(true,"验证购物车列表的有效商品数据");
		 try {
			 String productId = SellerProductCallService.addNewProductOnSale(sellerId, 
					 sellerName, null).getJSONObject("Data").getString("ProductID");
			 /*String liveProductId = SellerProductCallService.addNewProductOnSale(sellerId, 
					 sellerName, null).getJSONObject("Data").getString("ProductID");
			 String activityProductId = SellerProductCallService.addNewProductOnSale(sellerId, 
					 sellerName, null).getJSONObject("Data").getString("ProductID");
			 
			 SellerProductCallService.approveActivity(sellerId, activityUser, activityPswd, String.valueOf(activityStartId), activityProductId);
			 int liveId = LiveCallService.createLiveInProgress(sellerName, sellerId, fileName).getJSONObject("Data").getInt("ActivityId");
			 SellerProductCallService.addProductInLive(sellerId, liveId, liveProductId);*/
			 
			 BuyerAppShoppingCartService buyerAppShoppingCartService = new BuyerAppShoppingCartService();
			 buyerAppShoppingCartService.clearInvalidProductList(buyerUserId);
			 buyerAppShoppingCartService.addShoppingCart(productId, buyerUserId, 1);
			 //buyerAppShoppingCartService.addShoppingCart(liveProductId, buyerUserId, 1);
			 //buyerAppShoppingCartService.addShoppingCart(activityProductId, buyerUserId, 1);
			 
			 getShoppingCartListBean.setExcludeSellerCoupon(false);
			 getShoppingCartListBean.setGroupByPromotion(true);
			 getShoppingCartListBean.setUserId(buyerUserId);
			 
			 getShoppingCartListCall.setData(getShoppingCartListBean);
			 getShoppingCartListCall.callService();
			 
			 Logger.comment("getShoppingCartListCall send:" + getShoppingCartListCall.getEntityString());
			 Logger.comment("getShoppingCartListCall response:" + getShoppingCartListCall.getReturnData());
			 
			 this.verifyValidProdListData(getShoppingCartListCall);
			 
		 } catch (Exception e) {
			 Logger.fail(e);
		 }
	 }
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void verifyInvalidProdListData(GetShoppingCartListCall getShoppingCartListCall) throws Exception {
		ShoppingCartMongoWapper shoppingCartMongoWapper = new ShoppingCartMongoWapper();
		HashMap<String, ArrayList> hashMap = this.getProdListFromMongo(shoppingCartMongoWapper);
		ArrayList<YmtShoppcartListProductBean> expectInvalidProdList = hashMap.get("invalidProdList");
		
		Set<String> keyPathsSet = new HashSet<String>();
		
		JSONArray actualInvalidProdList = getShoppingCartListCall.getInvalidProdList();
		
		Iterator it = actualInvalidProdList.getJSONObject(0).keys();
		Collection c = new HashSet();
		while(it.hasNext())
		{
			String temp = it.next().toString();
			
			if (temp.equalsIgnoreCase("addTime"))
				continue;
			else
				c.add(temp);
		}
		
		keyPathsSet.addAll(c);
		for (int i = 0; i < expectInvalidProdList.size(); i++){
			Logger.comment(expectInvalidProdList.get(i).getId());
			AssertService.assertResultEqual(keyPathsSet, new JSONObject(FormatUtil.beanToGSONString(expectInvalidProdList.get(i))),
					actualInvalidProdList.getJSONObject(i));
		}
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void verifyValidProdListData(GetShoppingCartListCall getShoppingCartListCall) throws Exception {
		 
		ShoppingCartMongoWapper shoppingCartMongoWapper = new ShoppingCartMongoWapper();
		HashMap<String, ArrayList> hashMap = this.getProdListFromMongo(shoppingCartMongoWapper);
		ArrayList<YmtShoppcartListProductBean> expectValidProdList = hashMap.get("validProdList");
		
		Set<String> keyPathsSet =  new HashSet<String>();
		
		keyPathsSet.clear();
		JSONArray actualValidProdList = getShoppingCartListCall.getValidProdList();
		Iterator it = actualValidProdList.getJSONObject(0).keys();
		Collection c = new HashSet();
		while(it.hasNext())
		{
			String temp = it.next().toString();
			
			if (temp.equalsIgnoreCase("addTime"))
				continue;
			else
				c.add(temp);
		}
		
		keyPathsSet.addAll(c);
		for (int i = 0; i < expectValidProdList.size(); i++){
			Logger.comment(expectValidProdList.get(i).getId());
			AssertService.assertResultEqual(keyPathsSet, new JSONObject(FormatUtil.beanToGSONString(expectValidProdList.get(i))),
					actualValidProdList.getJSONObject(i));
		}	
	}
	
	/**
	 * 根据商品状态，获取有效商品和失效商品的合集
	 * 
	 * @param part
	 * @return HashMap<String, ArrayList>
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public HashMap<String, ArrayList> getProdListFromMongo(ShoppingCartMongoWapper wapper) throws Exception {
		HashMap<String, ArrayList> map = new HashMap<String, ArrayList>();
		ArrayList<YmtShoppcartListProductBean> validProdList = new ArrayList<YmtShoppcartListProductBean>();
		ArrayList<YmtShoppcartListProductBean> invalidProdList = new ArrayList<YmtShoppcartListProductBean>();
		
		//ArrayList<YmtShoppingCartBean> notInfo = (ArrayList<YmtShoppingCartBean>) wapper.getYmtShoppingCartInfoList("{'userid':" + buyerUserId + ", 'productid':'32b1f7e4-b68a-4144-8941-e33656e83868'}", 101);
		ArrayList<YmtShoppingCartBean> notInfo = (ArrayList<YmtShoppingCartBean>) wapper.getYmtShoppingCartInfoList("{'userid':" + buyerUserId + "}", 101);
		BuyerAppProdService buyerAppProdService = new BuyerAppProdService();
		ProductDetailModelWapper productDetailModelWapper = new ProductDetailModelWapper();
		
		for(YmtShoppingCartBean bean : notInfo) {
			Thread.sleep(1000);
			Map<String, Object> productMap = productDetailModelWapper.getProductId(bean.getProductid());
			YmtShoppcartListProductBean ymtShoppcartListProductBean = new YmtShoppcartListProductBean();
			LiveProductModelWapper liveProductModelWapper = new LiveProductModelWapper();
			Map activityProductMap = buyerAppProdService.getActivityByCatalogIdFromMongo(bean.getProductid(), bean.getCatalogid());
			JSONObject catalogObject = buyerAppProdService.getCatalogFromMongo(bean.getProductid(), bean.getCatalogid());
			JSONObject normalCatalogStockObject = buyerAppProdService.getCatalogStockFromMongo(0, bean.getProductid(), bean.getCatalogid());
			JSONObject activityCatalogStockObject = buyerAppProdService.getCatalogStockFromMongo(1, bean.getProductid(), bean.getCatalogid());
			JSONObject catalogPriceObject = buyerAppProdService.getCatalogPriceFromMongo(bean.getUserid(), bean.getSellerid(), bean.getProductid(), bean.getCatalogid());
		
			ymtShoppcartListProductBean.setScId(bean.get_id());
			ymtShoppcartListProductBean.setId(bean.getProductid());
			ymtShoppcartListProductBean.setCatalogId(bean.getCatalogid());
			ymtShoppcartListProductBean.setPic(bean.getPic());
			ymtShoppcartListProductBean.setProductType(buyerAppProdService.getProductTypeFromMongo(bean.getProductid()));
			ymtShoppcartListProductBean.setTariffType(bean.getTarifftype());
			ymtShoppcartListProductBean.setRefundType(bean.getRefundtype());
			ymtShoppcartListProductBean.setDescription(bean.getProductname());
				
			if (catalogPriceObject == null) {
				ymtShoppcartListProductBean.setPrice(bean.getPrice());
				ymtShoppcartListProductBean.setPriceType(0);
			} else {
				ymtShoppcartListProductBean.setPrice(String.valueOf(catalogPriceObject.getInt("Price")));
				ymtShoppcartListProductBean.setPriceType(catalogPriceObject.getInt("PriceType"));
			}
			
			JSONArray propertyList =  buyerAppProdService.getPropertyListFromMongo(bean.getProductid(), bean.getCatalogid());
			String skuInfo = "";
			
			for (int i = 0; i < propertyList.length(); i++) {
				String propertyName = propertyList.getJSONObject(i).getString("Name");
				String propertyValue = propertyList.getJSONObject(i).getString("Value");
				
				if ("null".equalsIgnoreCase(propertyName) && "null".equalsIgnoreCase(propertyValue))
					skuInfo = "";
				else
					skuInfo = skuInfo + ";" + propertyName + ":" + propertyValue;
			}
			
			if (skuInfo.startsWith(";")) {
				ymtShoppcartListProductBean.setSkuInfo(skuInfo.substring(1));
			} else {
				ymtShoppcartListProductBean.setSkuInfo(skuInfo);
			}
			
			if (activityProductMap != null) {
				ymtShoppcartListProductBean.setRemainStock(activityCatalogStockObject.getInt("Stock"));
				ymtShoppcartListProductBean.setStockDesc(this.getProductStockDesc(activityCatalogStockObject.getInt("Stock")));
				if (activityCatalogStockObject.getInt("Stock") == 0) 
						ymtShoppcartListProductBean.setState(1);
			} else {
				ymtShoppcartListProductBean.setRemainStock(normalCatalogStockObject.getInt("Stock"));
				ymtShoppcartListProductBean.setStockDesc(this.getProductStockDesc(normalCatalogStockObject.getInt("Stock")));
				if (normalCatalogStockObject.getInt("Stock") == 0)
					ymtShoppcartListProductBean.setState(1);
			}
			
			if (buyerAppProdService.getProductTypeFromMongo(bean.getProductid()) == 1) {
				Map<String, Object> liveProductModelMap = liveProductModelWapper.
						getByProductId(bean.getProductid());
				int second = YMTDateUtil.diffSecond(new Date().getTime(), 
						this.getCST2TimeStamp(liveProductModelMap.get("EndTime").toString()));
				
				if (second < 3600)
					ymtShoppcartListProductBean.setRestTime(second);
				else
					ymtShoppcartListProductBean.setRestTime(-1);
			}
			else 
				ymtShoppcartListProductBean.setRestTime(-1);
			
			ymtShoppcartListProductBean.setSellerId(bean.getSellerid());
			ymtShoppcartListProductBean.setDeliveryType(bean.getDeliverytype());
			ymtShoppcartListProductBean.setPurchaseNum(bean.getNum());
			
			ymtShoppcartListProductBean.setState(0);
			if (this.getCST2TimeStamp(productMap.get("ValidEnd").toString()) < new Date().getTime() || 
					null == catalogObject)
				ymtShoppcartListProductBean.setState(2);
			
			ymtShoppcartListProductBean.setAddTime(this.getShoppingcartTime(bean.getCreatetime().toString()));
			ymtShoppcartListProductBean.setNoReasonReturn(bean.getIsnoreasonreturn());
			
			if (activityProductMap != null) {
				ymtShoppcartListProductBean.setActivityName(activityProductMap.get("ActivityBuyerName").toString());
			} else {
				ymtShoppcartListProductBean.setActivityName("");
			}
			
			ymtShoppcartListProductBean.setSingleCatalog(bean.getIssinglecatalog());
				
			if (null == catalogObject || !catalogObject.has("IsPreSale"))
				ymtShoppcartListProductBean.setPreSale(false);
			else
				ymtShoppcartListProductBean.setPreSale(catalogObject.getBoolean("IsPreSale"));
			
			if (ymtShoppcartListProductBean.isPreSale()) 
				ymtShoppcartListProductBean.setPreSaleDesc("预订商品，需采购");
			else
				ymtShoppcartListProductBean.setPreSaleDesc("");
			
			ymtShoppcartListProductBean.setVersion(bean.getVersion());
			ymtShoppcartListProductBean.setShowSnapshot(this.getShowSnapshot(bean.getVersion(), productMap.get("Version").toString()));
			
			if (ymtShoppcartListProductBean.getState() == 0)
				validProdList.add(ymtShoppcartListProductBean);
			else
				invalidProdList.add(ymtShoppcartListProductBean);
		}
		
		map.put("validProdList", validProdList);
		map.put("invalidProdList", invalidProdList);

		return map;
	}
	
	/**
	 * 获取有效商品中所有的买手信息
	 * 
	 * @param part
	 * @return ArrayList<Integer>
	 * @throws JSONException 
	 * @throws Exception
	 */
	public ArrayList<Integer> getValidProdSellerId(ArrayList<JSONObject> productList) throws JSONException {
		ArrayList<Integer> sellerList = new ArrayList<Integer>();
		
		for (JSONObject product : productList)
		{
			if (sellerList.size() == 0) {
				sellerList.add(product.getInt("sellerid"));
			}
			else {
				if (!sellerList.contains(product.getInt("sellerid")))
					sellerList.add(product.getInt("sellerid"));
			}
		}
		
		return sellerList;
	}
	
	/**
	 * 判断商品是否需要跳转快照
	 * 
	 * @param shoppingcartVersion(存入购物车时的商品版本)，productVersion(最新的商品版本)
	 * @return Boolean
	 * @throws JSONException 
	 * @throws Exception
	 */
	public Boolean getShowSnapshot(String shoppingcartVersion, String productVersion) throws Exception {
		if (shoppingcartVersion.equalsIgnoreCase("0"))
			return false;
		else {
			int shoppingcartBigVersion = Integer.valueOf(shoppingcartVersion.split("\\.")[0]);
			int productBigVersion = Integer.valueOf(productVersion.split("\\.")[0]) / 1000;
			
			if (shoppingcartBigVersion < productBigVersion)
				return true;
			else
				return false;
		}
	}
	
	/**
	 * 判断库存描述
	 * 
	 * @param stock
	 * @return Integer
	 * @throws JSONException 
	 * @throws Exception
	 */
	public String getProductStockDesc(int stock) throws Exception {
		if (stock > 5) 
			return "";
		else
			return "仅剩" + stock + "件";
	}
	
	/**
	 * 判断包邮包税
	 * 
	 * @param catalogId
	 * @return Integer
	 * @throws JSONException 
	 * @throws Exception
	 */
	public int getProductTariffType(int freight, int tariffType) throws Exception {
		if (freight == 0 && tariffType == 0)
			return 1;
		else if(freight > 0 && tariffType == 0)
			return 2;
		else if(freight == 0 && tariffType > 0)
			return 3;
		else
			return 0;
	}

	/**
	 * 
	 * 获取商品规格的状态
	 * @param productId, catalogId
	 * @return Integer(如果找到catalogId且商品没有过期，则返回0，否则返回2)
	 * @throws JSONException 
	 * @throws Exception
	 */
	public int getProductStateFromMongo(String productId, String catalogId) throws Exception {
		
		ProductDetailModelWapper productDetailModelWapper = new ProductDetailModelWapper();
		Map<String, Object> productDetailModelMap = productDetailModelWapper.getProductId(productId);
		
		if (this.getCST2TimeStamp(productDetailModelMap.get("ValidEnd").toString()) < new Date().getTime())
			return 2;
		
		JSONArray catalogList = new JSONArray(productDetailModelMap.get("CatalogList").toString());
		for (int i = 0; i < catalogList.length(); i++) {
			if (catalogList.getJSONObject(i).getString("CatalogId") == catalogId)
				return 0;
		}
		
		return 2;
	}
	
	public long getCST2TimeStamp(String dateStr) {
		return YMTDateUtil.CST2TimeStamp(dateStr);
	}
	
	public String getShoppingcartTime(String dateStr) {
		return YMTDateUtil.CST2ShoppingcartTime(dateStr);
	}
	
	public static void main(String[] args) {
		String test = "3166001.0";
		
		String productBigVersion = String.valueOf(((Integer.valueOf(test.split("\\.")[0]) / 1000)));
		System.out.println(productBigVersion);
	}
}
